// start variables
var geocoder;
var map;

//user marker for map in def pos
var userMarker;
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
// first view configuration
var startMapViewZoom = 9; // start zoom for our map
var mapCoordinatesLength = 6; // Latitude & Longitude capasity
// Kiev coordinates (KPI)
var defaultStartLatitude = 50.447892;
var defaultStartLongitude = 30.451584;

var warehouses = new Array();

function initialize() {
    directionsDisplay = new google.maps.DirectionsRenderer();
    geocoder = new google.maps.Geocoder();
    var mapOptions = {
        zoom: startMapViewZoom,
        center: new google.maps.LatLng(defaultStartLatitude, defaultStartLongitude),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map(document.getElementById('googlemap'), mapOptions);
    directionsDisplay.setMap(map);
    // creates a draggable marker to the given coords
    userMarker = new google.maps.Marker({
        map: map,
        position: new google.maps.LatLng(defaultStartLatitude, defaultStartLongitude),
        draggable: false,
        animation: google.maps.Animation.DROP,
        title: 'Customer'
    });

    // adds a animation listener to the marker
//  google.maps.event.addListener(userMarker, 'click', toggleBounce);
}

function showWarehouses() {
    for (var i = 0; i < warehouses.length; i++) {
        warehouses[i] = new google.maps.Marker({
            map: map,
            position: warehouses[i].getPosition(),
            dragable: false,
            icon: 'http://google-maps-icons.googlecode.com/files/factory.png',
            animation: google.maps.Animation.DROP,
            title: warehouses[i].name
        });
    }
}

function addWarehouse(latitude, logitude, name) {
    warehouses.push(new google.maps.Marker({
        map: map,
        position: new google.maps.LatLng(latitude, logitude),
        draggable: false,
        icon: 'http://google-maps-icons.googlecode.com/files/factory.png',
        animation: google.maps.Animation.DROP,
        title: name
    }));
}
// search customer address

function codeAddress(address, callback) {
    geocoder.geocode({'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            callback(results);
            setMarkerPosition(results, 0);
        } else {
            console.log("Geocode was not successful: " + status);
        }
    });
}

function selectBestWarehouse() {
    var start = new google.maps.LatLng($("#start").find(":selected").attr('latitude'),
            $("#start").find(":selected").attr('longitude'));
    var options = document.getElementById("start").options;
    var minDist = Number.MAX_VALUE;
    var end = userMarker.getPosition();
    var minIndex = 0;
    for (var i = 0; i < options.length; i++) {
        var start = new google.maps.LatLng($(options[i]).attr('latitude'),
                $(options[i]).attr('longitude'));
        var dist = calcDistance(start, end);
        if (dist - minDist < 0) {
            minDist = dist;
            minIndex = i;
        }
    }
    return minIndex;
}

// animation function
//function toggleBounce() {
//    if (userMarker.getAnimation() != null) {
//        userMarker.setAnimation(null);
//    } else {
//        userMarker.setAnimation(google.maps.Animation.NONE);
//    }
//}
// calculates distance between two points in km's
function calcDistance(p1, p2) {
    return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(4);
}

function calcRouteFromWarehouse() {
    var start = new google.maps.LatLng($("#start").find(":selected").attr('latitude'),
            $("#start").find(":selected").attr('longitude'));
    var end = userMarker.getPosition();
    var yourDistance = calcDistance(start, end);
    var request = {
        origin: start,
        destination: end,
        travelMode: google.maps.TravelMode.DRIVING
    };
    $('#distance').text(Math.round(yourDistance));
//  document.getElementById('distance').value = Math.round(yourDistance);
    directionsService.route(request, function(result, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(result);
        }
    });
}


function setMarkerPosition(results, index) {
    map.setCenter(results[index].geometry.location);
    userMarker.setPosition(results[index].geometry.location);
    var latitude = userMarker.position.lat();
    var longitude = userMarker.position.lng();
    setCoordinates(latitude, longitude);
}
;

function setCoordinates(lat, long) {
    defaultStartLatitude = lat;
    defaultStartLongitude = long;
    $('#latitude').prop('value', lat);
    $('#longitude').prop('value', long);
}

$(document).ready(function() {
    initialize();
    showWarehouses();
});
//google.maps.event.addDomListener(window, 'load', initialize);
//showWarehouses();
